<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<!-- 2 加上app指令-->
<!--view开始-->
<body ng-app="myApp">
    <div ng-controller="mycontroller">
        用户名：<input type="text" ng-model="username"><br>
        密码：<input type="text" ng-model="password"><br>
        确认密码：<input type="text" ng-model="confirmP"><br>
        同意协议：<input type="checkbox" ng-model="ifAgree" ><br>
        <input type="button" ng-click="register()" value="注册">
        <ouput>{{msg}}</ouput>
    </div>
<!--view结束-->
    <!-- 1 引入angular-->
    <script src="angular/angular.js"></script>
    <script>


        <!--3 创建模版-->
        var myApp = angular.module('myApp',[]);

        <!--controller开始-->
        <!--4 创建构造器-->
        myApp.controller('mycontroller',function($scope){
            <!--初始化数据模型-->

            $scope.username = '';
            $scope.password = '';
            $scope.confirmP = '';
            $scope.ifAgree = false;
            $scope.msg = '';

            <!--初始化行为模型-->
            $scope.register = function(){
                <!--对数据进行验证-->
                if($scope.username.length>6){
                    $scope.msg = '用户名超过6个';
                    return;
                }
                if($scope.password!==$scope.confirmP){
                    $scope.msg = '两次密码不一致';
                    return;
                }
                if( !$scope.ifAgree ){
                   $scope.msg = '请同意协议'; 
                   return;
                }

                var user = new User($scope.username , $scope.password);
                if( user.save() ){
                    $scope.msg = '注册成功';
                }else {
                    $scope.msg = '用户名已经存在';
                }

            }

        })

        function User(name,pass){
            this.name = name;
            this.pass = pass;
        }
        User.prototype.save = function(){

            <!--从本地获取存储的用户名，返回的是一个json形式的字符串 [{'username':***,"password":***},...] -->

            var data = localStorage.getItem('user')||"[]";

            <!--将字符串转换成对象-->
            var users = JSON.parse(data);
            

            for( var i = 0 ; i < users.length ; i ++){
                if( this.name === users[i].username ){
                    return false;
                }
            }
            <!--不存在就添加-->
            users.push( { username:this.name , password : this.pass} );

            <!--存储的也是字符串形式-->

            localStorage.setItem( "user" , JSON.stringify(users) );

            return true;

        }

    </script>
</body>
</html>